package com.hzcx.app.simplechat.ui.chat;

import android.app.Service;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.hzcx.app.simplechat.R;
import com.hzcx.app.simplechat.base.BaseActivity;
import com.hzcx.app.simplechat.ui.chat.bean.ChatQuickMsgBean;
import com.hzcx.app.simplechat.ui.chat.contract.ChatQuickMsgAddContract;
import com.hzcx.app.simplechat.ui.chat.event.ChatQuickMsgRefreshEvent;
import com.hzcx.app.simplechat.ui.chat.presenter.ChatQuickMsgAddPresenter;
import com.hzcx.app.simplechat.ui.setting.adapter.ImgAdapter;
import com.hzcx.app.simplechat.util.UserInfoUtil;
import com.hzcx.app.simplechat.util.empty.EmptyUtils;
import com.hzcx.app.simplechat.util.log.LogUtils;
import com.hzcx.app.simplechat.util.photo.PhotoUtil;
import com.hzcx.app.simplechat.view.autogridview.PhotoLoader;
import com.hzcx.app.simplechat.view.autogridview.PhotoProgressUi;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import indi.liyi.viewer.ImageViewer;

/**
 * 添加快捷回复
 */
public class ChatQuickMsgAddActivity extends BaseActivity<ChatQuickMsgAddPresenter> implements ChatQuickMsgAddContract.View, OnResultCallbackListener<LocalMedia>,
        BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.OnItemChildClickListener {

    public static final String INTENT_CONTENT = "INTENT_CONTENT";
    public static final String INTENT_ID = "INTENT_ID";
    public static final String INTENT_IMAGE_URL = "INTENT_IMAGE_URL";
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_title_right)
    ImageView ivTitleRight;
    @BindView(R.id.tv_title_right)
    TextView tvTitleRight;
    @BindView(R.id.et_content)
    EditText etContent;
    @BindView(R.id.rv_img)
    RecyclerView rvImg;
    @BindView(R.id.imageViewer)
    ImageViewer imageViewer;
    @BindView(R.id.ll_img)
    LinearLayout llImg;


    private String id;
    private String imgUrl;

    private List<String> imgList;
    private ImgAdapter imgAdapter;
    private List<LocalMedia> seleteImgList;
    private boolean isSelectImg = false;
    private ChatQuickMsgBean quickMsgBean;

    @Override
    public int getLayout() {
        return R.layout.activity_chat_quick_msg_add;
    }

    @Override
    public void initPresenter() {
        mPresenter = new ChatQuickMsgAddPresenter();
    }

    @Override
    public void initView() {
        tvTitle.setText("添加常用语");
        tvTitleRight.setText("完成");
        imageViewer.imageLoader(new PhotoLoader());

        etContent.setText(getIntent().getStringExtra(INTENT_CONTENT));

        seleteImgList = new ArrayList<>();
        imgList = new ArrayList<>();
        if (EmptyUtils.isNotEmpty(getIntent().getStringExtra(INTENT_IMAGE_URL))) {
            quickMsgBean = new Gson().fromJson(getIntent().getStringExtra(INTENT_IMAGE_URL), ChatQuickMsgBean.class);
            if (quickMsgBean.getReply_images_arr() != null && quickMsgBean.getReply_images_arr().size() > 0) {
                for (ChatQuickMsgBean.ReplyImagesArrBean bean : quickMsgBean.getReply_images_arr()) {
                    imgList.add(bean.getImgurl());
                }
            }
        }
        imgAdapter = new ImgAdapter(R.layout.rv_item_img, imgList);
        rvImg.setLayoutManager(new GridLayoutManager(this, 3));
        rvImg.setAdapter(imgAdapter);

        // 会员才可以添加图片
        if (UserInfoUtil.getUserIsVip()) {
            llImg.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void initData() {
        id = getIntent().getStringExtra(INTENT_ID);

        tvTitleRight.setOnClickListener(view -> {
            if (EmptyUtils.isEmpty(etContent.getText().toString())) {
                showError("请填写内容");
                return;
            }
            if (seleteImgList.size() > 0) {
                showLoading();
                mPresenter.upLoadImg(ChatQuickMsgAddActivity.this, seleteImgList);
            } else {
                String images = "";
                if (quickMsgBean != null && quickMsgBean.getReply_images_arr() != null && quickMsgBean.getReply_images_arr().size() > 0) {
                    for (int i = 0; i < quickMsgBean.getReply_images_arr().size(); i++) {
                        if (i < quickMsgBean.getReply_images_arr().size() - 1) {
                            images = images + quickMsgBean.getReply_images_arr().get(i).getImgurl() + ",";
                        } else {
                            images = images + quickMsgBean.getReply_images_arr().get(i).getImgurl();
                        }
                    }
                }
                mPresenter.addQuickMsg(ChatQuickMsgAddActivity.this, etContent.getText().toString(), id, images);
            }
        });

        imgAdapter.setOnItemClickListener(this);
        imgAdapter.setOnItemChildClickListener(this);
        helper.attachToRecyclerView(rvImg);

        // 添加初始值
        imgList.add("");
        imgAdapter.notifyDataSetChanged();
    }

    /**
     * 添加成功
     */
    @Override
    public void addSuccess() {
        showError("添加成功");
        EventBus.getDefault().post(new ChatQuickMsgRefreshEvent(0, 0));
        finish();
    }

    /**
     * 图片上传成功
     *
     * @param url
     */
    @Override
    public void upLoadSuccess(String url) {
        hideLoading();
        String images = "";
        if (quickMsgBean != null && quickMsgBean.getReply_images_arr() != null && quickMsgBean.getReply_images_arr().size() > 0) {
            for (int i = 0; i < quickMsgBean.getReply_images_arr().size(); i++) {
                images = images + quickMsgBean.getReply_images_arr().get(i).getImgurl() + ",";
            }
        }
        mPresenter.addQuickMsg(this, etContent.getText().toString(), id, images + url);
    }

    /**
     * 图片选取返回
     *
     * @param result
     */
    @Override
    public void onResult(List<LocalMedia> result) {
        if (imgList.size() + result.size() > 9) {
            showError("最多只能添加9张图片");
            return;
        }
        isSelectImg = true;
        seleteImgList.clear();
        seleteImgList.addAll(result);
        imgList.clear();
        if (quickMsgBean != null && quickMsgBean.getReply_images_arr() != null && quickMsgBean.getReply_images_arr().size() > 0) {
            for (ChatQuickMsgBean.ReplyImagesArrBean bean : quickMsgBean.getReply_images_arr()) {
                imgList.add(bean.getImgurl());
            }
        }
        for (LocalMedia media : result) {
            imgList.add(PhotoUtil.getPath(media));
        }
        if (imgList.size() < 9) {
            imgList.add(imgList.size(), "");
        }
        imgAdapter.notifyDataSetChanged();
    }

    @Override
    public void onCancel() {

    }

    /**
     * 子控件点击
     *
     * @param adapter
     * @param view
     * @param position
     */
    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        switch (view.getId()) {
            case R.id.iv_delete:
                deleteImg(position);
                break;
        }
    }

    /**
     * 图片列表点击
     *
     * @param adapter
     * @param view
     * @param position
     */
    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        if (EmptyUtils.isEmpty(imgList.get(position))) {
            PhotoUtil.showPhoto(this, PictureMimeType.ofImage(), PictureConfig.MULTIPLE, true, false, seleteImgList, this);
        } else {
//            PhotoUtil.openPhoto(this, seleteImgList, position);
            List<String> list = new ArrayList<>();
            for (String str : imgList) {
                if (EmptyUtils.isNotEmpty(str)) {
                    list.add(str);
                }
            }
            imageViewer.overlayStatusBar(true)
                    .imageData(list)
                    .loadProgressUI(new PhotoProgressUi())
                    .watch(position);
        }
    }

    /**
     * 删除图片
     *
     * @param pos
     */
    private void deleteImg(int pos) {
        if (seleteImgList != null && seleteImgList.size() > 0 && pos < seleteImgList.size()) {
            int deleteIndex = -1;
            for (int i = 0; i < seleteImgList.size(); i++) {
                if (imgList.get(pos).equals(PhotoUtil.getPath(seleteImgList.get(i)))) {
                    deleteIndex = i;
                    break;
                }
            }
            if (deleteIndex != -1) {
                LogUtils.d("删除：" + deleteIndex);
                seleteImgList.remove(deleteIndex);
            }
        }
        imgList.remove(pos);
        if (quickMsgBean != null && quickMsgBean.getReply_images_arr() != null && pos < quickMsgBean.getReply_images_arr().size()) {
            quickMsgBean.getReply_images_arr().remove(pos);
        }
        if (EmptyUtils.isNotEmpty(imgList.get(imgList.size() - 1))) {
            imgList.add(imgList.size(), "");
        }
        imgAdapter.notifyDataSetChanged();
    }


    ItemTouchHelper helper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
        @Override
        public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
            int dragFrlg = 0;
            if (recyclerView.getLayoutManager() instanceof GridLayoutManager) {
                dragFrlg = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
            } else if (recyclerView.getLayoutManager() instanceof LinearLayoutManager) {
                dragFrlg = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
            }
            return makeMovementFlags(dragFrlg, 0);
        }

        @Override
        public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
            //滑动事件  下面注释的代码，滑动后数据和条目错乱，被舍弃
//            Collections.swap(datas,viewHolder.getAdapterPosition(),target.getAdapterPosition());
//            ap.notifyItemMoved(viewHolder.getAdapterPosition(),target.getAdapterPosition());

            //得到当拖拽的viewHolder的Position
            int fromPosition = viewHolder.getAdapterPosition();
            //拿到当前拖拽到的item的viewHolder
            int toPosition = target.getAdapterPosition();
            if (fromPosition < toPosition) {
                for (int i = fromPosition; i < toPosition; i++) {
                    Collections.swap(imgList, i, i + 1);
                }
            } else {
                for (int i = fromPosition; i > toPosition; i--) {
                    Collections.swap(imgList, i, i - 1);
                }
            }
            imgAdapter.notifyItemMoved(fromPosition, toPosition);
            return true;
        }

        @Override
        public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
            //侧滑删除可以使用；
        }

        @Override
        public boolean isLongPressDragEnabled() {
            return true;
        }

        /**
         * 长按选中Item的时候开始调用
         * 长按高亮
         * @param viewHolder
         * @param actionState
         */
        @Override
        public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
            if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
                //获取系统震动服务//震动70毫秒
                Vibrator vib = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE);
                vib.vibrate(70);
            }
            super.onSelectedChanged(viewHolder, actionState);
        }

        /**
         * 手指松开的时候还原高亮
         * @param recyclerView
         * @param viewHolder
         */
        @Override
        public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
            super.clearView(recyclerView, viewHolder);
            viewHolder.itemView.setBackgroundColor(0);
            imgAdapter.notifyDataSetChanged();  //完成拖动后刷新适配器，这样拖动后删除就不会错乱
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
